﻿using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Query.SqlExpressions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace S.Services.SheepMale.Infrastructure
{
    public class BaseRepository<T> : IRepository<T> where T : class, new()
    {
        private readonly EntityDbContext db;

        public BaseRepository(EntityDbContext db)
        {
            this.db = db;
        }
        public async Task<IQueryable<T>> AllAsync()
        {
            var result = await Task.FromResult(db.Set<T>().AsQueryable());
            return result;
        }

        public async Task<int> BatchDeleteAsync(string id)
        {
            DbSet<T> dbset=db.Set<T>();
            var result = dbset.FindAsync(id);
            db.Remove(result);
            return await db.SaveChangesAsync();
        }

        public async Task<int> CreateAsync(T entity)
        {
            db.Set<T>().AddAsync(entity);
            return await db.SaveChangesAsync();
        }

        public async Task<int> DeleteAllAsync(Expression<Func<T, bool>> expression)
        {
            DbSet<T> dbset= db.Set<T>();
            var result = dbset.Where(expression);
            db.RemoveRange(result);
            return await db.SaveChangesAsync();
        }

        public async Task<int> DeleteAsync(int id)
        {
            DbSet<T> dbset = db.Set<T>();
            var result = dbset.Find(id);
            db.Remove(result);
            return await db.SaveChangesAsync();
        }

        public async Task<T> GetAsync(int id)
        {
            DbSet<T> dbset=db.Set<T>();
            return await dbset.FindAsync(id);
        }

        //public async Task<List<T>> GetValues(Expression<Func<T, bool>> expression)
        //{
        //    DbSet<T> dbset = db.Set<T>();
        //    return await dbset.Where(expression).ToList();
        //}

        public async Task<int> UpdateAsync(T entity)
        {
            db.Update(entity);
            return await db.SaveChangesAsync();
        }
    }
}
